﻿#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : BaseEditor(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    table=KIM_PASSWD;

    listModel=new QStringListModel(this);
    ui->listView->setModel(listModel);

    model=new QSqlTableModel(this);
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    ui->tableView->setModel(model);
    createMenu();
    updateCategory();
    loadLocation();
    loadState();
}

Widget::~Widget()
{
    saveLocation();
    saveState();
    delete ui;
}

void Widget::saveState()
{
    auto category=ui->categories->currentText();
    if(category.isEmpty())
        return;

    QSettings cfg(configFile,QSettings::IniFormat);
    cfg.setValue("Category/last",category);
}

void Widget::loadState()
{
    QSettings cfg(configFile,QSettings::IniFormat);

    auto category=cfg.value("Category/last").toString();
    if(!category.isEmpty())
        ui->categories->setCurrentText(category);
}

void Widget::generateMenu()
{
    menu->addAction(QStringLiteral("新增... (F1)"),this,&Widget::newItem);
    menu->addAction(QStringLiteral("复制新增... (F2)"),this,&Widget::copyNewItem);
    menu->addSeparator();
    menu->addAction(QStringLiteral("复制账号 (Alt+1)"),this,&Widget::copyAccount);
    menu->addAction(QStringLiteral("复制密码 (Alt+2)"),this,&Widget::copyPasswd);
    menu->addSeparator();
    menu->addAction(QStringLiteral("打开 (Alt+W)"),this,&Widget::openSource);
    menu->addAction(QStringLiteral("编辑... (F3)"),this,&Widget::editItem);
    menu->addSeparator();
    QMenu *m_update=menu->addMenu(QStringLiteral("更新"));
    m_update->addAction(QStringLiteral("更新类别"),this,&Widget::updateCategory);
    m_update->addAction(QStringLiteral("更新列表 (F4)"),this,&Widget::updateListView);
    m_update->addAction(QStringLiteral("更新视图 (F5)"),this,&Widget::updateView);
}

void Widget::openSource()
{
    auto index=ui->tableView->currentIndex();
    if(!index.isValid())
        return;

    QString source=sp_fetchString(index,SRC_COL);
    if(source.isEmpty() || !source.contains("://"))
        return;

    if(source.startsWith("http"))
        QDesktopServices::openUrl(QUrl(source));
    else if(source.startsWith(PREFIX_RDP))
    {
        QString host=source.remove(PREFIX_RDP);
        QProcess::startDetached(QString(RDP_OPEN).arg(host));
    }
}

void Widget::newItem()
{
    P_AddItem item(this);
    item.exec();
}

void Widget::copyNewItem()
{
    auto index=ui->tableView->currentIndex();
    if(!index.isValid())
        return;

    int id=sp_fetchId(index);
    if(id != 0)
    {
        P_AddItem item(this);
        item.fetchById(id);
        item.exec();
    }
}

void Widget::editItem()
{
    auto index=ui->tableView->currentIndex();
    if(!index.isValid())
        return;

    int id=sp_fetchId(index);
    if(id != 0)
    {
        P_AddItem item(this);
        item.setId(id);
        item.exec();
    }
}

void Widget::removeItem()
{
    auto index=ui->tableView->currentIndex();
    if(index.isValid())
        model->removeRow(index.row());
}

void Widget::keyPressEvent(QKeyEvent *event)
{
    if(event->modifiers() == Qt::ControlModifier && event->key() == Qt::Key_S)
        save();
    else if(event->modifiers() == Qt::ControlModifier && event->key() == Qt::Key_Z)
        revert();
    else if(event->modifiers() == Qt::AltModifier && event->key() == Qt::Key_1)
        copyAccount();
    else if(event->modifiers() == Qt::AltModifier && event->key() == Qt::Key_2)
        copyPasswd();
    else if(event->modifiers() == Qt::AltModifier && event->key() == Qt::Key_W)
        openSource();
    else
    {
        switch (event->key()) {
        case Qt::Key_F1:
            newItem();
            break;
        case Qt::Key_F2:
            copyNewItem();
            break;
        case Qt::Key_F3:
            editItem();
            break;
        case Qt::Key_F4:
            updateListView();
            break;
        case Qt::Key_F5:
            updateView();
            break;
        case Qt::Key_Delete:
            removeItem();
            break;
        }
    }
}

void Widget::updateCategory()
{
    if(ui->categories->count() != 0)
        ui->categories->clear();

    auto items=sp_getCategory(table);
    ui->categories->addItems(items);
}

void Widget::on_categories_currentTextChanged(const QString &category)
{
    if(category.isEmpty())
        return;

    selectCategory=category;
    updateListView();
}

void Widget::updateListView()
{
    if(selectCategory.isEmpty())
        return;

    if(listModel->rowCount() != 0)
        listModel->setStringList(QStringList());

    QSqlQuery query;
    query.exec(QString("SELECT label from %1 WHERE category='%2' GROUP BY label")
               .arg(table).arg(selectCategory));
    QStringList items;
    while (query.next()) {
        QString label=query.value(0).toString();
        if(!label.isEmpty())
            items.append(label);
    }

    listModel->setStringList(items);
}

void Widget::on_listView_doubleClicked(const QModelIndex &index)
{
    if(index.isValid())
    {
        selectLabel=index.data().toString();
        updateView();
    }
}

void Widget::updateView()
{
    if(selectCategory.isEmpty() || selectLabel.isEmpty())
        return;

    model->setTable(table);
    model->setFilter(QString("category='%1' AND label='%2'")
                     .arg(selectCategory)
                     .arg(selectLabel));
    model->select();
    ui->tableView->hideColumn(ID_COL);
    ui->tableView->hideColumn(CAT_COL);
    ui->tableView->hideColumn(LAB_COL);
    ui->tableView->hideColumn(PWD_COL);
    ui->tableView->resizeColumnToContents(SRC_COL);
    ui->status->clear();
}

void Widget::copyAccount()
{
    auto index=ui->tableView->currentIndex();
    if(!index.isValid())
        return;

    QString item=sp_fetchString(index,ACC_COL);
    if(item.isEmpty())
        return;

    qApp->clipboard()->setText(item);
    ui->status->setText("账号已复制到剪贴板");
}

void Widget::copyPasswd()
{
    auto index=ui->tableView->currentIndex();
    if(!index.isValid())
        return;

    QString item=sp_fetchString(index,PWD_COL);
    if(item.isEmpty())
        return;

    qApp->clipboard()->setText(item);
    ui->status->setText("密码已复制到剪贴板");
}

/*
void Widget::on_tableView_doubleClicked(const QModelIndex &index)
{
    QString passwd=sp_fetchString(index,PWD_COL);
    if(passwd.isEmpty())
        return;

    qApp->clipboard()->setText(passwd);
    ui->status->setText("密码已复制到剪贴板");
}
*/

void Widget::on_kw_editingFinished()
{
    QString kw=ui->kw->text().trimmed();
    if(kw.isEmpty())
        return;

    model->setTable(table);
    model->setFilter(QString("label like '%%1%' OR source like '%%1%'")
                     .arg(kw));
    model->select();
    ui->tableView->hideColumn(ID_COL);
    ui->tableView->hideColumn(CAT_COL);
    ui->tableView->hideColumn(PWD_COL);
    ui->status->clear();
}
